import { Injectable } from '@angular/core'
import { Store } from '@ngxs/store'
import localeZh from '@angular/common/locales/zh-Hans'
import { registerLocaleData } from '@angular/common'
import { UpdateDictAction } from '@app/store/action/dict.action'
import { SystemService } from '@app/services/system.service'

import { zip } from 'rxjs'
import { map } from 'rxjs/operators'
/**
 * 用于应用启动时
 * 一般用来获取应用所需要的基础数据等
 */
@Injectable()
export class StartupService {
  constructor(private store: Store, private systemService: SystemService) {}

  private async registerLocaleData() {
    registerLocaleData(localeZh, 'zh-cn')
  }

  private async getSystemParams() {
    zip(
      this.systemService.getCommonParamters(),
      this.systemService.getAssetParamters().pipe(
        map(data =>
          data.map(x => ({
            paramCode: 'asset',
            paramLabel: x.assetName,
            paramValue: x.assetCode
          }))
        )
      ),
      this.systemService.getInteractParamters().pipe(
        map(data =>
          data.map(x => ({
            paramCode: 'interact',
            paramLabel: x.interactName,
            paramValue: x.interactCode
          }))
        )
      )
    )
      .toPromise()
      .then(([commonDict, assetDict, interactDict]) => {
        const data = Object.assign(commonDict, { asset: assetDict, interact: interactDict })
        this.store.dispatch(new UpdateDictAction(data))
      })
      .catch(() => {})
  }

  public load(): Promise<any> {
    return Promise.all([this.registerLocaleData(), this.getSystemParams()])
  }
}
